import React, { useState, useEffect } from 'react';
import { Card, Button, Space, message, Row, Col, Input } from '@/utils/antd-imports';
import { companyApi } from '@/api/companyApi';
import { customerApi } from '@/api/customerApi';
import captchaApi from '@/api/captchaApi';
import employeeApi from '@/api/employeeApi';

const TestPage = () => {
  const [companyCount, setCompanyCount] = useState(0);
  const [customerCount, setCustomerCount] = useState(0);
  const [employeeCount, setEmployeeCount] = useState(0);
  const [loading, setLoading] = useState(false);
  const [captchaData, setCaptchaData] = useState(null);
  const [captchaCode, setCaptchaCode] = useState('');
  const [captchaLoading, setCaptchaLoading] = useState(false);

  // 测试公司API
  const testCompanyApi = async () => {
    setLoading(true);
    try {
      const response = await companyApi.getAllCompanies();
      if (response.code === 200) {
        setCompanyCount(response.data?.length || 0);
        message.success(`公司API测试成功，共 ${response.data?.length || 0} 条记录`);
      }
    } catch (error) {
      message.error('公司API测试失败');
      console.error('公司API测试失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 测试客户API
  const testCustomerApi = async () => {
    setLoading(true);
    try {
      const response = await customerApi.getAllCustomers();
      if (response.code === 200) {
        setCustomerCount(response.data?.length || 0);
        message.success(`客户API测试成功，共 ${response.data?.length || 0} 条记录`);
      }
    } catch (error) {
      message.error('客户API测试失败');
      console.error('客户API测试失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 测试员工API
  const testEmployeeApi = async () => {
    setLoading(true);
    try {
      const response = await employeeApi.getEmployeeList({
        page: 1,
        size: 10,
        status: 1
      });
      if (response.code === 200) {
        setEmployeeCount(response.data?.total || 0);
        message.success(`员工API测试成功，共 ${response.data?.total || 0} 条记录`);
      }
    } catch (error) {
      message.error('员工API测试失败');
      console.error('员工API测试失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 测试分页查询
  const testPagination = async () => {
    setLoading(true);
    try {
      const [companyResponse, customerResponse, employeeResponse] = await Promise.all([
        companyApi.getCompanyList({ page: 1, size: 5 }),
        customerApi.getCustomerList({ page: 1, size: 5 }),
        employeeApi.getEmployeeList({ page: 1, size: 5, status: 1 })
      ]);

      if (companyResponse.code === 200 && customerResponse.code === 200 && employeeResponse.code === 200) {
        message.success('分页查询测试成功');
        console.log('公司分页数据:', companyResponse.data);
        console.log('客户分页数据:', customerResponse.data);
        console.log('员工分页数据:', employeeResponse.data);
      }
    } catch (error) {
      message.error('分页查询测试失败');
      console.error('分页查询测试失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 测试验证码API
  const testCaptchaApi = async () => {
    setCaptchaLoading(true);
    try {
      const response = await captchaApi.generateCaptcha();
      if (response.code === 200) {
        setCaptchaData(response.data);
        message.success('验证码生成成功');
        console.log('验证码数据:', response.data);
      } else {
        message.error(response.message || '验证码生成失败');
      }
    } catch (error) {
      message.error('验证码API测试失败');
      console.error('验证码API测试失败:', error);
    } finally {
      setCaptchaLoading(false);
    }
  };

  // 验证验证码
  const verifyCaptcha = async () => {
    if (!captchaData || !captchaCode) {
      message.error('请先生成验证码并输入验证码');
      return;
    }

    try {
      const response = await captchaApi.verifyCaptcha({
        captchaId: captchaData.captchaId,
        captchaCode: captchaCode
      });
      
      if (response.code === 200) {
        message.success('验证码验证成功');
      } else {
        message.error(response.message || '验证码验证失败');
      }
    } catch (error) {
      message.error('验证码验证失败');
      console.error('验证码验证失败:', error);
    }
  };

  return (
    <div style={{ padding: '24px' }}>
      <h1>API接口测试页面</h1>
      
      <Row gutter={16}>
        <Col span={8}>
          <Card title="公司主体API测试" style={{ marginBottom: 16 }}>
            <Space direction="vertical" style={{ width: '100%' }}>
              <div>
                <strong>当前公司数量:</strong> {companyCount}
              </div>
              <Button 
                type="primary" 
                onClick={testCompanyApi}
                loading={loading}
                block
              >
                测试公司API
              </Button>
            </Space>
          </Card>
        </Col>
        
        <Col span={8}>
          <Card title="客户信息API测试" style={{ marginBottom: 16 }}>
            <Space direction="vertical" style={{ width: '100%' }}>
              <div>
                <strong>当前客户数量:</strong> {customerCount}
              </div>
              <Button 
                type="primary" 
                onClick={testCustomerApi}
                loading={loading}
                block
              >
                测试客户API
              </Button>
            </Space>
          </Card>
        </Col>

        <Col span={8}>
          <Card title="员工信息API测试" style={{ marginBottom: 16 }}>
            <Space direction="vertical" style={{ width: '100%' }}>
              <div>
                <strong>当前员工数量:</strong> {employeeCount}
              </div>
              <Button 
                type="primary" 
                onClick={testEmployeeApi}
                loading={loading}
                block
              >
                测试员工API
              </Button>
            </Space>
          </Card>
        </Col>
      </Row>

      <Card title="分页查询测试">
        <Button 
          type="primary" 
          onClick={testPagination}
          loading={loading}
        >
          测试分页查询
        </Button>
      </Card>

      <Card title="验证码API测试" style={{ marginTop: 16 }}>
        <Space direction="vertical" style={{ width: '100%' }}>
          <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
            <Button 
              type="primary" 
              onClick={testCaptchaApi}
              loading={captchaLoading}
            >
              生成验证码
            </Button>
            {captchaData && captchaData.captchaImage && (
              <div 
                style={{ 
                  width: '120px', 
                  height: '40px', 
                  border: '1px solid #d9d9d9', 
                  borderRadius: '6px',
                  display: 'flex', 
                  alignItems: 'center', 
                  justifyContent: 'center',
                  cursor: 'pointer',
                  backgroundColor: '#fafafa',
                  overflow: 'hidden'
                }}
                onClick={testCaptchaApi}
                title="点击刷新验证码"
              >
                <img
                  src={captchaData.captchaImage}
                  alt="验证码"
                  style={{ 
                    width: '100%', 
                    height: '100%', 
                    objectFit: 'cover',
                    cursor: 'pointer'
                  }}
                />
              </div>
            )}
          </div>
          
          {captchaData && (
            <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
              <Input
                placeholder="请输入验证码"
                value={captchaCode}
                onChange={(e) => setCaptchaCode(e.target.value)}
                maxLength={4}
                style={{ width: '120px' }}
              />
              <Button 
                onClick={verifyCaptcha}
                disabled={!captchaCode}
              >
                验证验证码
              </Button>
            </div>
          )}
        </Space>
      </Card>
    </div>
  );
};

export default TestPage;